package com.sany.taskmanager.ui.widget;

import android.content.Context;

import androidx.annotation.NonNull;

import com.sany.taskmanager.R;
import com.sany.taskmanager.bean.FactoryBean;
import com.sany.taskmanager.databinding.DialogFactoryBinding;
import com.sany.taskmanager.manager.DataManager;
import com.sany.taskmanager.ui.adapter.FactoryAdapter;

import java.util.List;

/**
 * 厂区选择弹框
 */
public class FactoryDialog extends CommonDialog<DialogFactoryBinding> {
    private FactoryAdapter mAdapter;
    private List<FactoryBean> mFactoryList;
    private OnFactoryListener mOnFactoryListener;
    private String mFactoryCode;

    public void setOnFactoryListener(OnFactoryListener onFactoryListener) {
        mOnFactoryListener = onFactoryListener;
    }

    public FactoryDialog(@NonNull Context context) {
        this(context, "");
    }

    public FactoryDialog(@NonNull Context context, String factoryCode) {
        super(context, context.getString(R.string.title_factory_select));
        mFactoryCode = factoryCode;
    }

    @Override
    protected void initData() {
        mAdapter = new FactoryAdapter(mContext);
        vBinding.rvFactory.setAdapter(mAdapter);
        mFactoryList = DataManager.getInstance().getFactoryList();
        refreshList();
    }

    private void refreshList() {
        int selectedIndex = -1;
        for (int i = 0; i < mFactoryList.size(); i++) {
            if (mFactoryList.get(i).getFactoryCode().equals(mFactoryCode)) {
                selectedIndex = i;
                break;
            }
        }
        mAdapter.setList(mFactoryList, selectedIndex);
    }

    @Override
    protected boolean confirm() {
        int selectedIndex = mAdapter.getSelectedIndex();
        if (mOnFactoryListener != null) {
            mOnFactoryListener.getFactory(mFactoryList.get(selectedIndex));
        }
        return true;
    }

    public interface OnFactoryListener {
        void getFactory(FactoryBean factoryBean);
    }

}
